package com.shiguiwu.springboot3.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.shiguiwu.springboot3.dto.AuthUser;
import com.shiguiwu.springboot3.dto.response.LoginResponse;
import com.shiguiwu.springboot3.util.JwtUtils;
import com.shiguiwu.springboot3.util.ServletUtil;
import jakarta.servlet.http.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: token服务
 * @author: stone
 * @date: Created by 2025/10/26 18:07
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.service
 */
@Service
public class TokenService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisService redisService;


    public final static String REDIS_TOKEN_MEMBER_KEY = "member_key:token";

    public LoginResponse createToken(AuthUser authenticate) {
        // 生成双Token
        String accessToken = this.getToken(authenticate);
        String refreshToken = jwtUtils.generateRefreshToken(authenticate.getUsername());

        // 将refresh_token存入Redis
        redisService.storeRefreshToken(authenticate.getUsername(), refreshToken, jwtUtils.getRefreshExpiration());

        // 设置refresh_token到HttpOnly Cookie
        Cookie refreshTokenCookie = new Cookie("refresh_token", refreshToken);
        refreshTokenCookie.setHttpOnly(true);
        refreshTokenCookie.setSecure(true); // 仅HTTPS传输
        refreshTokenCookie.setPath("/auth/refresh");
        refreshTokenCookie.setMaxAge((int) (jwtUtils.getAccessExpiration() / 1000));
        ServletUtil.getResponse().addCookie(refreshTokenCookie);

        // 返回access_token和用户信息
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setRefreshToken(refreshToken);
        loginResponse.setAccessToken(accessToken);
        loginResponse.setTokenType("Bearer");
        loginResponse.setExpiresIn(jwtUtils.getAccessExpiration());
        //loginResponse.setAuthUser(authenticate);
        return loginResponse;
    }


    public String getToken(AuthUser authenticate) {
        String uuid = UUID.fastUUID().toString();
        redisService.setHashValue(REDIS_TOKEN_MEMBER_KEY, uuid, JSONUtil.toJsonStr(authenticate));

        return  jwtUtils.generateAccessToken(uuid);
    }

    public AuthUser getToken(String token) {
        //String uuid = UUID.fastUUID().toString();
        Object hashValue = redisService.getHashValue(REDIS_TOKEN_MEMBER_KEY, token);

        return  JSONUtil.toBean(hashValue.toString(), AuthUser.class);
    }


    public void deleteToken(String token) {
        String extractToken = jwtUtils.extractToken(token);
        redisService.delHashValue(REDIS_TOKEN_MEMBER_KEY, extractToken);
    }
}
